<template>
  <div>
    <a-input-search
        id="search-input"
        placeholder="请输入关键字"
        enter-button="搜索"
        @search="handleSearchRecipes"
        style="width: 30%"
    />
    <br>
    <br>
    <br>
    <br>
    <div class="recipe-cards">
      <a-card v-for="recipe in recipes" :key="recipe.recipe_id" :bodyStyle="{ padding: '16px' }">
        <template #cover>
          <a-image :src="recipe.image_url" style="width: 60%;" />
        </template>
        <div class="card-title">{{ recipe.title }}</div>
        <p>{{ recipe.description }}</p>
        <div><span>发布者: {{ recipe.user_id }}</span></div>
      </a-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { notification } from 'ant-design-vue';

// 定义食谱数据列表
const recipes = ref([]);

// 获取食谱数据
const handleFetchRecipes = () => {
  const token = localStorage.getItem('token');
  const config = {
    headers: {
      'Token': token,
    },
  };

  axios.get('/recipe/lists', config)
      .then((response) => {
        const data = response.data;
        if (data.code === 0) {
          recipes.value = data.data;
        } else {
          notification.error({ description: data.message });
        }
      })
      .catch((error) => {
        notification.error({ description: '没有得到数据' + error });
      });
};

// 处理搜索请求
const handleSearchRecipes = (value) => {
  const token = localStorage.getItem('token');
  const config = {
    headers: {
      'Token': token,
    },
  };

  axios.get(`/recipe/search?keyword=${value}`, config)
      .then((response) => {
        const data = response.data;
        if (data.code === 0) {
          recipes.value = data.data;
        } else {
          notification.error({ description: data.message });
        }
      })
      .catch((error) => {
        notification.error({ description: '搜索失败' + error });
      });
};

// 在组件挂载时加载数据
onMounted(() => {
  handleFetchRecipes();
});
</script>

<style scoped>
.recipe-cards {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
}

.recipe-cards > .ant-card {
  width: calc(33% - 20px); /* 调整为适合你的布局的宽度 */
  margin-bottom: 20px;
}

.card-title {
  /* 你可以在这里添加一些样式来确保它看起来像标题 */
  font-size: 1.25em;
  font-weight: bold;
  margin-bottom: 10px;
}

@media (max-width: 768px) {
  .recipe-cards > .ant-card {
    width: calc(50% - 20px);
  }
}

@media (max-width: 480px) {
  .recipe-cards > .ant-card {
    width: 100%;
  }
}
</style>